package com.wty.cmims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.pojo.Appointment;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.Medication;
import com.wty.cmims.pojo.Prescription;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.service.AppointmentService;
import com.wty.cmims.service.MedicalHistoryService;
import com.wty.cmims.service.MedicationService;
import com.wty.cmims.service.PrescriptionService;
import com.wty.cmims.mapper.PrescriptionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* @author wty
* @description 针对表【prescription】的数据库操作Service实现
* @createDate 2024-12-17 01:01:03
*/
@Service
public class PrescriptionServiceImpl extends ServiceImpl<PrescriptionMapper, Prescription>
    implements PrescriptionService{
    @Autowired
    MedicalHistoryService medicalHistoryService;
    @Autowired
    MedicationService medicationService;
    @Autowired
    AppointmentService appointmentService;
    @Override
    public ResponseResult<Map<String, Object>> prescriptionFindByAppointmentId(Integer appointmentId) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<MedicalHistory> wrapperhistory = new LambdaQueryWrapper<>();
        wrapperhistory.eq(MedicalHistory::getAppointmentId, appointmentId);
        Integer historyId = medicalHistoryService.getOne(wrapperhistory).getId();

        LambdaQueryWrapper<Prescription> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Prescription::getHistoryId, historyId);
        Prescription prescription = this.getOne(wrapper);

        Map<String, Object> history = medicalHistoryService.medicalHistoryfind(appointmentId).getData();

        Map<String, Object> prescriptionMap = new HashMap<>();
        List<Map<String, Object>> medicationsArray = new ArrayList<>();
        if (prescription != null){
            // 用这个Map存储Prescription
            prescriptionMap.put("id", prescription.getId());
            prescriptionMap.put("historyId", prescription.getHistoryId());
            prescriptionMap.put("residentId", prescription.getResidentId());
            prescriptionMap.put("institutionId", prescription.getInstitutionId());
            prescriptionMap.put("departmentId", prescription.getDepartmentId());
            prescriptionMap.put("doctorId", prescription.getDoctorId());
            prescriptionMap.put("medications", prescription.getMedications());
            prescriptionMap.put("makeDate", prescription.getMakeDate());
            // 名称
            prescriptionMap.put("resident", history.get("resident"));
            prescriptionMap.put("doctor", history.get("doctor"));
            prescriptionMap.put("institution", history.get("institution"));
            prescriptionMap.put("department", history.get("department"));

            // 取出medications
            String medications = prescription.getMedications();
            // 分割为若干个“id*count”
            String[] split = medications.split(",");
            Set<Integer> medicationIds = new HashSet<>();
            Map<Integer, String> idToNumMap = new HashMap<>();

            for (String s : split) {
                // 取出一个“id*count”，分割为id和count
                String[] item = s.split("\\*");
                int id = Integer.parseInt(item[0]);
                medicationIds.add(id);
                idToNumMap.put(id, item[1]);
            }

            // 批量查询药品信息
            List<Medication> medicationsList = medicationService.listByIds(medicationIds);
            for (Medication medication : medicationsList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", medication.getId());
                map.put("name", medication.getName());
                map.put("indications", medication.getIndications());
                map.put("price", medication.getPrice());
                map.put("specification", medication.getSpecification());
                map.put("unit", medication.getUnit());
                map.put("dosage", medication.getDosage());
                map.put("precautions", medication.getPrecautions());
                map.put("adverseEffects", medication.getAdverseEffects());
                map.put("expirationDate", medication.getExpirationDate());
                map.put("isOTC", medication.getIsOtc());
                map.put("manufacturer", medication.getManufacturer());
                map.put("approvalNumber", medication.getApprovalNumber());
                map.put("medicationImg", medication.getMedicationImg());
                map.put("isDel", medication.getIsDel());
                map.put("count", Integer.parseInt(idToNumMap.get(medication.getId())));
                medicationsArray.add(map);
            }
        }
        if (!medicationsArray.isEmpty()){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("存在处方");
            responseResult.setData(prescriptionMap);
            responseResult.setDatas(medicationsArray);
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("不存在处方");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<List<Map<String, Object>>> prescriptionFindByResidentId(Integer residentId) {
        ResponseResult<List<Map<String, Object>>> responseResult = new ResponseResult<>();

        LambdaQueryWrapper<Prescription> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Prescription::getResidentId, residentId);
        wrapper.orderByDesc(Prescription::getId);
        List<Prescription> prescriptions = this.list(wrapper);
        // 查询所有appointment_id
        List<Integer> appointmentIds = new ArrayList<>();
        for (Prescription prescription : prescriptions) {
            appointmentIds.add(prescription.getAppointmentId());
        }
        if (!appointmentIds.isEmpty()){
            List<Map<String, Object>> otherInfoArray = new ArrayList<>();
            List<List<Map<String, Object>>> prescriptionsArray = new ArrayList<>();
            ResponseResult<Map<String, Object>> result = null;
            for (Integer appointmentId : appointmentIds) {
                result = prescriptionFindByAppointmentId(appointmentId);
                otherInfoArray.add(result.getData());
                prescriptionsArray.add(result.getDatas());
            }
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("查询成功");
            responseResult.setData(otherInfoArray);
            responseResult.setDatas(prescriptionsArray);
        }
        return responseResult;
    }
}